package com.jy.datapipeline.export.controller;

import com.jy.datapipeline.common.constants.ExcelConstants;
import com.jy.datapipeline.common.support.EasyExcelSupport;
import com.jy.datapipeline.common.support.ExcelSupport;
import com.jy.datapipeline.common.vo.ReturnVo;
import com.jy.datapipeline.export.entity.ExpRuleModel;
import com.jy.datapipeline.export.entity.ExpTaskModel;
import com.jy.datapipeline.export.entity.RuleTemplateModel;
import com.jy.datapipeline.export.service.ExpRuleDetailService;
import com.jy.datapipeline.export.service.ExpRuleService;
import com.jy.datapipeline.export.service.ExpTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
    @RequestMapping(value = "/exprule/")
public class ExpRuleController {
    @Autowired
    private ExpRuleService expRuleService;
    @Autowired
    private ExpRuleDetailService expRuleDetailService;

    @Autowired
    private ExpTaskService expTaskService;

    @Resource
    private EasyExcelSupport easyExcelSupport;

    @Resource
    private ExcelSupport excelSupport;

    @RequestMapping( value = "findByList",method = RequestMethod.GET)
    @ResponseBody
    public Object findDataStoreByList(
        @RequestParam(value = "dataSourceName",required = true) String dataSourceName,
        @RequestParam(value = "ruleName",required = true) String ruleName,
        @RequestParam(value = "iDisplayStart",required = true) Integer iDisplayStart,
            @RequestParam(value = "iDisplayLength",required = true) Integer iDisplayLength
    ){
        Map<String, Object> map=new HashMap<>();
        List<Map<String,Object>> list=this.expRuleService.findExpRuleByList(dataSourceName,ruleName,iDisplayStart,iDisplayLength);
        Integer count=this.expRuleService.findExpRuleByCount(dataSourceName,ruleName);
        map.put("datalist",list);
        map.put("count", count);
        return map;
    }

    @RequestMapping( value = "add",method = RequestMethod.POST)
    @ResponseBody
    public Object add(
        @RequestParam(value = "dataSourceId",required = true) String dataSourceId,
        @RequestParam(value = "ruleName",required = true) String ruleName,
        @RequestParam(value = "col_separator",required = true) String colSeparator,
        @RequestParam(value = "file_name_rule",required = false) String fileNameRule,
        @RequestParam(value = "is_file",required = true) int isFile
    ){
        Map<String, Object> result=new HashMap<>();
        try{
            String ruleId= "rule_"+String.valueOf(System.currentTimeMillis());
            ExpRuleModel erm=new ExpRuleModel();
            erm.setDataSourceId(dataSourceId);
            erm.setRuleId(ruleId);
            erm.setColSeparator(colSeparator);
            erm.setFileNameRule(fileNameRule);
            erm.setRuleName(ruleName);
            erm.setIsFile(isFile);
            ExpRuleModel ermInfo= this.expRuleService.findByRuleName(ruleName);
            if(ermInfo==null){
                this.expRuleService.saveExpRule(erm);
                result.put("status",true);
                result.put("msg","success");
            }else {
                result.put("status",false);
                result.put("msg","规则名称重复");
            }
        }catch (Exception e){
            log.error("add exception",e);
            result.put("msg","error ["+e.getMessage()+"]");
            result.put("status",false);
        }
        return result;
    }

    @RequestMapping( value = "update",method = RequestMethod.POST)
    @ResponseBody
    public Object update(
        @RequestParam(value = "dataSourceId",required = true) String dataSourceId,
        @RequestParam(value = "ruleName",required = true) String ruleName,
        @RequestParam(value = "col_separator",required = true) String colSeparator,
        @RequestParam(value = "file_name_rule",required = false) String fileNameRule,
        @RequestParam(value = "ruleId",required = true) String ruleId,
        @RequestParam(value = "is_file",required = true) int isFile
    ){
        Map<String, Object> result=new HashMap<>();
        try{
            ExpRuleModel erm=new ExpRuleModel();
            erm.setDataSourceId(dataSourceId);
            erm.setRuleId(ruleId);
            erm.setColSeparator(colSeparator);
            erm.setFileNameRule(fileNameRule);
            erm.setRuleName(ruleName);
            erm.setIsFile(isFile);
            ExpRuleModel ermInfo= this.expRuleService.findByRuleId(ruleId);
            boolean isUpdate=false;
            if(ermInfo!=null){
                if(!ruleName.equals(ermInfo.getRuleName())){
                    ExpRuleModel ermInfo2=this.expRuleService.findByRuleName(ruleName);
                    if(ermInfo2!=null){
                        result.put("status",false);
                        result.put("msg","规则名称重复");
                        return result;
                    }else{
                        isUpdate=this.expRuleService.updateExpRule(erm);
                    }

                }else{
                    isUpdate=this.expRuleService.updateExpRule(erm);
                }

                result.put("status",isUpdate);
                result.put("msg",isUpdate?"success":"修改失败");
            }else{
                result.put("status",false);
                result.put("msg","数据源信息不存在");
            }

        }catch (Exception e){
            log.error("update exception");
            result.put("msg","error ["+e.getMessage()+"]");
            result.put("status",false);
        }
        return result;
    }

    @RequestMapping( value = "deleteByRuleId",method = RequestMethod.POST)
    @ResponseBody
    public Object deleteById(
        @RequestParam(value = "ruleId",required = true) String ruleId
    ){
        Map<String, Object> result=new HashMap<>();
        try{
          //
//          List<ExpTaskModel> expTaskModelList=  expTaskService.findByRuleId(ruleId);
//          if(expTaskModelList.size()==0){
//              boolean flag=this.expRuleService.deleteByRuleId(ruleId);
//              this.expRuleDetailService.deleteByRuleId(ruleId);
//              result.put("status",flag);
//              result.put("msg","success");
//          }
          //List<Map<String,Object>> list=  this.expRuleService.findRuleInfoByTask(ruleId,1);
            List<ExpTaskModel> list= expTaskService.findByRuleId(ruleId);
          if(list.size()==0){

            boolean flag=this.expRuleService.deleteByRuleId(ruleId);
            this.expRuleDetailService.deleteByRuleId(ruleId);
            result.put("status",flag);
            result.put("msg","success");
          }else{
              result.put("status",false);
              result.put("msg","请先删除关联的导出任务");
          }
        }catch (Exception e){
            log.error("deleteById exception");
            result.put("msg","error ["+e.getMessage()+"]");
            result.put("status",false);
        }
        return result;
    }
    @RequestMapping( value = "findAllByDataSourceId",method = RequestMethod.GET)
    @ResponseBody
    public Object findAllByDataSourceId(
        @RequestParam(value = "dataSourceId",required = true) String  dataSourceId
    ){
        Map<String, Object> result=new HashMap<>();
        try{
            List<ExpRuleModel> expRuleModelList= this.expRuleService.findByDataSourceId(dataSourceId);
            //List<Map<String,Object>> list=this.expRuleService.findExpRuleByList(null,null,-1,-1);
            result.put("data",expRuleModelList);
            result.put("status",true);
            result.put("msg","success");
        }catch (Exception e){
            log.error("findAll exception");
            result.put("msg","error ["+e.getMessage()+"]");
            result.put("status",false);
        }
        return result;
    }

    @RequestMapping( value = "findByRuleId",method = RequestMethod.GET)
    @ResponseBody
    public Object findAll(
        @RequestParam(value = "ruleId",required = true) String  ruleId
    ){
        Map<String, Object> result=new HashMap<>();
        try{

            ExpRuleModel erm= this.expRuleService.findByRuleId(ruleId);
            result.put("data",erm);
            result.put("status",true);
            result.put("msg","success");
        }catch (Exception e){
            log.error("findAll exception");
            result.put("msg","error ["+e.getMessage()+"]");
            result.put("status",false);
        }
        return result;
    }

    @GetMapping("/download")
    public void downloadRuleTemplate(HttpServletResponse res) throws IOException {
        excelSupport.downloadTemplate(res,
                ExcelConstants.EXPORT_RULE_TEMPLATE_COLUMNS,
                ExcelConstants.EXPORT_RULE_TEMPLATE_COMMENTS,
                ExcelConstants.EXPORT_RULE_TEMPLATE_SHEET_NAME,
                ExcelConstants.EXPORT_RULE_TEMPLATE_EXAMPLE,
                ExcelConstants.EXPORT_RULE_TEMPLATE_NAME
        );
    }

    @PostMapping("/upload")
    public ReturnVo updateRuleTemplate(@RequestBody MultipartFile file) throws IOException {
        easyExcelSupport.analysisTemplate(file.getInputStream(), 10, expRuleService, RuleTemplateModel.class);
        return ReturnVo.ok();
    }
}
